﻿using System.Drawing;

namespace Common.Core
{
    public static class StreamByteImageConverter
    {
        public static byte[] StreamToByteArr(Stream stream)
        {
            byte[] bytes = new byte[stream.Length]; //创建byte数组
            stream.Read(bytes, 0, bytes.Length); //将Stream读入byte数组
            stream.Seek(0, SeekOrigin.Begin);// 将流指向起始位置
            return bytes;
        }

        public static Image BytesToImage(byte[] bytes)
        {
            Image photo = null;
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                ms.Write(bytes, 0, bytes.Length);
                photo = Image.FromStream(ms, true);
            }
            return photo;
        }

        public static byte[] ImageToBytes(Image img)
        {
            byte[] bt = null;
            if (!img.Equals(null))
            {
                using (MemoryStream mostream = new MemoryStream())
                {
                    Bitmap bmp = new Bitmap(img);
                    bmp.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);
                    bt = new byte[mostream.Length];
                    mostream.Position = 0;
                    mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
                }
            }
            return bt;
        }
    }
}
